package com.leeoohoo.base;

import com.leeoohoo.common.UserContext;
import com.leeoohoo.common.UserHolder;
import com.oohoo.spacestationspringbootstarter.dto.query.DTO;
import com.oohoo.spacestationspringbootstarter.dto.query.EPage;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;

public abstract class BaseController<T, ID, PD extends PageDTO, SD extends DTO> {

    public abstract BaseService<T, ID> getService();


    @PostMapping("save")
    public Mono<Result<Void>> save(@RequestBody @Validated Mono<SD> sdMono) {
        UserContext myUser = UserHolder.getMyUser();
        return sdMono.map(it -> {
            UserHolder.setMyUser(myUser);
            this.getService().save(it);
            return Result.success();
        });
    }

    @DeleteMapping("delete")
    public Mono<Result<Void>> delete(@RequestParam("id") ID id) {
        this.getService().deleteById(id);
        return Mono.just(Result.success());
    }

    @DeleteMapping("logicDelete")
    public Mono<Result<Void>> logicDelete(@RequestParam("id") ID id) {
        UserContext myUser = UserHolder.getMyUser();
        this.getService().logicDelete(id);
        return Mono.just(Result.success());
    }

    @GetMapping("getById")
    public Mono<Result<T>> getById(@RequestParam("id") ID id) {
        return Mono.justOrEmpty(Result.success(this.getService().get(id)));
    }

    @PostMapping("page")
    public Mono<Result<EPage<PD>>> page(@RequestBody Mono<PD> dto) {
        return dto.map(it -> Result.success(getService().page(it)));
    }


    @PostMapping("list")
    public Mono<Result<List<PD>>> list(@RequestBody Mono<PD> dto) {
        return dto.map(it -> Result.success(getService().list(it)));
    }
}
